package com.ssyc.student.activity;

import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ssyc.common.adapter.VpCommonAdapter;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.common.view.NoScrollViewPager;
import com.ssyc.student.R;
import com.ssyc.student.bean.DepotInfo;
import com.ssyc.student.fragment.StudentDepotClothingFragment;
import com.ssyc.student.fragment.StudentDepotFoodFragment;
import com.ssyc.student.fragment.StudentDepotPropFragment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 学生端--补给站
 * Created by Administrator on 2018/4/25 0025.
 */

public class StudentDepotActivity extends BaseActivity implements View.OnClickListener {
    //返回
    private ImageView ivBack;

    //加载
    private RelativeLayout rlLoading;
    //美食
    private ImageView lvFood;
    //服装
    private ImageView lvClothing;
    //道具
    private ImageView lvProp;
    //不可滚动ViewPager
    private NoScrollViewPager vp;

    //金币余额
    private TextView tvGold;

    //Tab页面选中的资源图片集合
    private int[] tabSelectIds = {R.drawable.st_food_select, R.drawable.st_clothing_select, R.drawable.st_prop_select};

    //Tab页面未选中的资源图片集合
    private int[] tabUnselectIds = {R.drawable.st_food_normal, R.drawable.st_clothing_normal, R.drawable.st_prop_normal};

    //填充ViewPager的页面
    private List<Fragment> mFragments;
    //ViewPager的适配器
    private VpCommonAdapter vpAdapter;

    //用户金币余额
    public int totalMoney;

    public int getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(int totalMoney) {
        this.totalMoney = totalMoney;
    }

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.student_activity_depot;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //获取服务器数据
        http();
    }

    /**
     * 获取补给站后台接口数据的网络请求的方法
     */
    private void http() {
        String acc = SPUtil.getString(this, SpKeys.ACCOUNT);
        String token = SPUtil.getString(this,SpKeys.TOKEN1);

        Map<String, String> map = HttpUtils.getStudentMap();
        map.put("type", "6");//固定
        map.put("petsex", SPUtil.getString(this,SpKeys.PETGENDAR));//宠物性别
        map.put("pettype", SPUtil.getString(this,SpKeys.SERVICEPETTYPE));//宠物类型
        map.put("acc",acc);//账号
        map.put("role","0");//角色
        map.put("apptoken",token);//token

        Log.i("test",HttpAdress.DEPOT+"?type=6&petsex="+SPUtil.getString(this,SpKeys.PETGENDAR)
        +"&pettype="+SPUtil.getString(this,SpKeys.SERVICEPETTYPE)+"&acc=13006314760&role=0&apptoken="
                +token);
        HttpUtils.post(HttpAdress.DEPOT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }

                UiUtils.Toast(BaseApplication.ERROR, false);
            }

            @Override
            public void onResponse(String response, int id) {

                //解析返回服务器返回的JSON数据
                if (null != rlLoading) {
                    rlLoading.setVisibility(View.GONE);
                }
                DepotInfo info = null;
                try {
                    info = GsonUtil.jsonToBean(response, DepotInfo.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("test", "解析服务器返回数据异常");
                }

                if (null != info) {
                    if ("200".equals(info.getState())) {
                        DepotInfo.DataBean dataBean = info.getData();
                        if (null != dataBean) {
                            //获取余额,保存并在页面上显示
                            setTotalMoney(dataBean.getCOIN());
                            tvGold.setText(getTotalMoney() + "");

                            //设置ViewPager
                            initVp(dataBean);
                        }
                    } else {
                        Log.i("test", "错误信息是:" + info.getState());
                    }
                }

            }
        });
    }

    /**
     * 初始化VieWPager
     */
    private void initVp(DepotInfo.DataBean dataBean) {
        mFragments = new ArrayList<>();
        mFragments.add(StudentDepotFoodFragment.newInstance(GsonUtil.listToJson(dataBean.getType_1())));
        mFragments.add(StudentDepotClothingFragment.newInstance(GsonUtil.listToJson(dataBean.getType_2())));
        mFragments.add(StudentDepotPropFragment.newInstance(GsonUtil.listToJson(dataBean.getType_3())));
        vpAdapter = new VpCommonAdapter(getSupportFragmentManager(), mFragments);
        vp.setOffscreenPageLimit(mFragments.size());
        vp.setAdapter(vpAdapter);
    }


    /**
     * 初始化视图
     */
    public void initView() {
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);
        lvFood = findViewById(R.id.lv_food);
        lvFood.setOnClickListener(this);
        tvGold = findViewById(R.id.tv_gold);
        lvClothing = findViewById(R.id.lv_clothing);
        lvClothing.setOnClickListener(this);
        lvProp = findViewById(R.id.lv_prop);
        lvProp.setOnClickListener(this);
        vp = findViewById(R.id.vp);
        vp.setPagerEnabled(false);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
    }

    /**
     * 页面控件点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.iv_back) {
            finish();
        } else if (id == R.id.lv_food) {
            //食物
            syncVpState(0);
        } else if (id == R.id.lv_clothing) {
            //服装
            syncVpState(1);
        } else if (id == R.id.lv_prop) {
            //道具
            syncVpState(2);
        }
    }


    /**
     * 同步ViewPager页面和切换选中Tab的方法
     *
     * @param pos
     */
    private void syncVpState(int pos) {
        vp.setCurrentItem(pos);
        if (pos == 0) {
            lvFood.setImageResource(tabSelectIds[0]);
            lvClothing.setImageResource(tabUnselectIds[1]);
            lvProp.setImageResource(tabUnselectIds[2]);
        } else if (pos == 1) {
            lvFood.setImageResource(tabUnselectIds[0]);
            lvClothing.setImageResource(tabSelectIds[1]);
            lvProp.setImageResource(tabUnselectIds[2]);
        } else if (pos == 2) {
            lvFood.setImageResource(tabUnselectIds[0]);
            lvClothing.setImageResource(tabUnselectIds[1]);
            lvProp.setImageResource(tabSelectIds[2]);
        }
    }

    /**
     * 通过EventBus更改当前页面的余额
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.useMoney != 0) {
            //计算剩余金币总数
            int leftMoney = getTotalMoney() - busInfo.useMoney;
            if (leftMoney > 0) {
                //更新保存的用户余额信息
                setTotalMoney(leftMoney);
            } else {
                setTotalMoney(0);
            }
            //同时更改页面显示的金币余额
            tvGold.setText(getTotalMoney() + "");
        }
    }
}
